package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;


    @Autowired
    private HuanXinTemplate huanXinTemplate;
    //发送验证码
    public void sendMsg(String phone) {
        //1. 随机生成六位验证码
        // String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2. 调用模板对象，发送手机短信
        //smsTemplate.sendSms(phone, code);
        //3. 将验证码存入redis， 五分钟
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));

    }

    //验证登录
    public Map<String, Object> loginVerification(String phone, String code) {
        //1. 从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        System.out.println("redisCode: " + redisCode);
        //2. 校验验证码（是否存在，是否一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            // 验证码为空，或不一致的时候，
            throw new BusinessException(ErrorResult.loginError());
        }

        //3. 删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);

        //4. 通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        //5. 判断用户（是否存在）
        boolean isNew = false;
        if (user == null) {
            user = new User();
            user.setCreated(new Date());
            user.setUpdated(new Date());
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        //6. 生成 token
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("mobile", phone);
        String token = JwtUtils.getToken(map);

        //7. 构造返回值
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("token", token);
        resMap.put("isNew", isNew);
        return resMap;
    }
}
